<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>实现底部导航栏</title>
  <link rel="stylesheet" href="css/nav.css">
</head>
<body>
  <div id="app">
    <div class="content">
      <h1>主页内容</h1>
    </div>
    <!-- 使用导航栏组件 -->
    <bottom-navbar-component></bottom-navbar-component>
  </div>
  <!-- 引入 Vue.js -->
  <script src="js/vue.js"></script>
  <script>
    // 定义底部导航栏组件
    Vue.component('bottom-navbar-component', {
      template: `
        <div class="bottom-navbar">   
          <navbar-item v-for="(tab, index) in navTabs" :key="index" :title="tab.title" :icon="tab.icon" @click="selectTab(index)"></navbar-item>
        </div>
      `,
      data() {
        return {
          navTabs: [
            { title: '首页', icon: 'images/nav-icon-home.png' },
            { title: '商品分类', icon: 'images/nav-icon-category.png' },
            { title: '购物车', icon: 'images/nav-icon-cart.png' },
            { title: '个人中心', icon: 'images/nav-icon-user.png' }
          ],  
          // 当前选中的导航项索引，初始设为0，即默认选中首页
          currentTabIndex: 0
        };
      },
      methods: {
        selectTab(index) {
          this.currentTabIndex = index;
          console.log(`选中了 ${this.navTabs[index].title}`);
        }
      },
      // 定义导航项组件
      components: {
        'navbar-item': {
          props: ['title', 'icon'],
          template: `
            <div class="navbar-item" :class="{ 'active': isActive }" @click="$emit('click')">
              <img :src="icon" alt="{{ title }}"> <span>{{ title }}</span>
            </div>
          `,
          computed: {
            isActive() {
              // 通过与父组件的当前选中索引对比，来判断自身是否处于选中状态
              return this.$parent.currentTabIndex === this.$vnode.key;
            }
          }
        }
      }
    });
    // 创建根实例
    new Vue({
      el: '#app'
    });
  </script>
</body>
</html>